import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  message,
  DatePicker,
  InputNumber,
  Tag,
  ConfigProvider,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { getActivityPage, addActivity, updateActivity, deleteActivity, ActivityInfo } from '@/services/ActivityService';
import { famousPersonId } from '@/services';
import dayjs from 'dayjs';
import styles from './index.less';
import zhCN from 'antd/locale/zh_CN';
import RichTextEditor from '@/components/RichTextEditor';

const { RangePicker } = DatePicker;

// 添加活动类型和状态的枚举定义
const ActivityType = {
  ONLINE: 1,
  OFFLINE: 2,
  LIVE: 3,
} as const;

const ActivityStatus = {
  NOT_STARTED: 0,
  IN_PROGRESS: 1,
  ENDED: 2,
  CANCELED: 3,
} as const;

const ActivityAdmin: React.FC = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState<ActivityInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingId, setEditingId] = useState<number>();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [searchForm] = Form.useForm();

  // 加载数据
  const loadData = async (page = pagination.current, pageSize = pagination.pageSize) => {
    try {
      setLoading(true);
      const values = await searchForm.validateFields();
      const response = await getActivityPage({
        pageCurrent: page,
        pageSize: pageSize,
        famousPersonId: famousPersonId,
        keyword: values.keyword,
        type: values.type,
        status: values.status,
      });
      setData(response.list);
      setPagination({
        current: page,
        pageSize: pageSize,
        total: response.totalCount,
      });
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      const submitData = {
        ...values,
        famousPersonId,
        startTime: values.time[0].format('YYYY-MM-DD HH:mm:ss'),
        endTime: values.time[1].format('YYYY-MM-DD HH:mm:ss'),
        registrationDeadline: values.registrationDeadline?.format('YYYY-MM-DD HH:mm:ss'),
      };

      if (editingId) {
        await updateActivity({ ...submitData, id: editingId });
        message.success('更新成功');
      } else {
        await addActivity(submitData);
        message.success('添加成功');
      }
      setModalVisible(false);
      loadData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理删除
  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个活动吗？删除后不可恢复。',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteActivity([id]);
          message.success('删除成功');
          loadData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理编辑
  const handleEdit = (record: ActivityInfo) => {
    setEditingId(record.id);
    form.setFieldsValue({
      ...record,
      time: [dayjs(record.startTime), dayjs(record.endTime)],
      registrationDeadline: record.registrationDeadline ? dayjs(record.registrationDeadline) : undefined,
    });
    setModalVisible(true);
  };

  // 添加搜索处理函数
  const handleSearch = () => {
    loadData(1);
  };

  const columns = [
    {
      title: '活动名称',
      dataIndex: 'title',
      key: 'title',
      width: '15%',
    },
    {
      title: '活动时间',
      key: 'activityTime',
      width: '20%',
      render: (_: any, record: ActivityInfo) => (
        <span style={{ whiteSpace: 'nowrap' }}>
          {dayjs(record.startTime).format('YYYY-MM-DD HH:mm')} 至 {dayjs(record.endTime).format('YYYY-MM-DD HH:mm')}
        </span>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: '25%',
      ellipsis: true,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: '10%',
      render: (type: number) => {
        const typeMap = {
          [ActivityType.ONLINE]: { text: '线上活动', color: 'blue' },
          [ActivityType.OFFLINE]: { text: '线下活动', color: 'green' },
          [ActivityType.LIVE]: { text: '直播活动', color: 'purple' },
        };
        return <Tag color={typeMap[type].color}>{typeMap[type].text}</Tag>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '10%',
      render: (status: number) => {
        const statusMap = {
          [ActivityStatus.NOT_STARTED]: { text: '未开始', color: 'default' },
          [ActivityStatus.IN_PROGRESS]: { text: '进行中', color: 'processing' },
          [ActivityStatus.ENDED]: { text: '已结束', color: 'success' },
          [ActivityStatus.CANCELED]: { text: '已取消', color: 'error' },
        };
        return <Tag color={statusMap[status].color}>{statusMap[status].text}</Tag>;
      },
    },
    {
      title: '参与人数',
      key: 'participants',
      width: '15%',
      render: (_: any, record: ActivityInfo) => (
        <span>
          {record.currentParticipants || 0}
          {record.maxParticipants ? `/${record.maxParticipants}` : ''}
        </span>
      ),
    },
    {
        title: '报名截止时间',
        dataIndex: 'registrationDeadline',
        key: 'registrationDeadline',
        width: '15%',
        render: (registrationDeadline: string) => (
            dayjs(registrationDeadline).isValid() ?
            <span>{dayjs(registrationDeadline).format('YYYY-MM-DD HH:mm')}</span> :
            <span>无</span>
        ),
    },
    {
      title: '操作',
      key: 'action',
      width: '15%',
      render: (_: any, record: ActivityInfo) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id!)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 修改搜索表单渲染函数
  const renderSearchForm = () => (
    <div className={styles.toolbarContent}>
      <Form
        form={searchForm}
        layout="inline"
        onFinish={handleSearch}
      >
        <Form.Item name="keyword">
          <Input
            placeholder="请输入活动名称/描述"
            allowClear
            prefix={<SearchOutlined />}
          />
        </Form.Item>
        <Form.Item name="type">
          <Select
            placeholder="活动类型"
            allowClear
            style={{ width: 120 }}
          >
            <Select.Option value={ActivityType.ONLINE}>线上活动</Select.Option>
            <Select.Option value={ActivityType.OFFLINE}>线下活动</Select.Option>
            <Select.Option value={ActivityType.LIVE}>直播活动</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item name="status">
          <Select
            placeholder="活动状态"
            allowClear
            style={{ width: 120 }}
          >
            <Select.Option value={ActivityStatus.NOT_STARTED}>未开始</Select.Option>
            <Select.Option value={ActivityStatus.IN_PROGRESS}>进行中</Select.Option>
            <Select.Option value={ActivityStatus.ENDED}>已结束</Select.Option>
            <Select.Option value={ActivityStatus.CANCELED}>已取消</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button onClick={() => {
              searchForm.resetFields();
              loadData(1, 20);
            }}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>
      <Button
        type="primary"
        icon={<PlusOutlined />}
        onClick={() => {
          setEditingId(undefined);
          form.resetFields();
          setModalVisible(true);
        }}
      >
        新增活动
      </Button>
    </div>
  );

  // 处理表格变化
  const handleTableChange = (newPagination: any) => {
    loadData(newPagination.current, newPagination.pageSize);
  };

  // 修改渲染模态框函数
  const renderModal = () => (
    <Modal
      title={editingId ? '编辑活动' : '新增活动'}
      open={modalVisible}
      onCancel={() => {
        setModalVisible(false);
        form.resetFields();
      }}
      footer={null}
      width={1200}
      styles={{
        body: {
          maxHeight: 'calc(100vh - 200px)',
          overflowY: 'auto',
          padding: '24px 32px',
        },
        header: {
          marginBottom: 0,
        },
      }}
      closeIcon={false}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        className={styles.modalForm}
      >
        <div className={styles.formContent}>
          <div className={styles.basicInfo}>
            <Form.Item
              name="title"
              label="活动名称"
              rules={[{ required: true, message: '请输入活动名称' }]}
            >
              <Input maxLength={100} />
            </Form.Item>

            <Form.Item
              name="description"
              label="活动简介"
              rules={[{ required: true, message: '请输入活动简介' }]}
            >
              <Input.TextArea rows={3} maxLength={500} showCount />
            </Form.Item>

            <Form.Item
              name="time"
              label="活动时间"
              rules={[{ required: true, message: '请选择活动时间' }]}
            >
              <RangePicker
                showTime
                style={{ width: '100%' }}
                placeholder={['开始时间', '结束时间']}
              />
            </Form.Item>

            <Form.Item
              name="location"
              label="活动地点"
            >
              <Input maxLength={100} />
            </Form.Item>

            <Form.Item
              name="type"
              label="活动类型"
              rules={[{ required: true, message: '请选择活动类型' }]}
            >
              <Select>
                <Select.Option value={ActivityType.ONLINE}>线上活动</Select.Option>
                <Select.Option value={ActivityType.OFFLINE}>线下活动</Select.Option>
                <Select.Option value={ActivityType.LIVE}>直播活动</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="status"
              label="活动状态"
              rules={[{ required: true, message: '请选择活动状态' }]}
            >
              <Select>
                <Select.Option value={ActivityStatus.NOT_STARTED}>未开始</Select.Option>
                <Select.Option value={ActivityStatus.IN_PROGRESS}>进行中</Select.Option>
                <Select.Option value={ActivityStatus.ENDED}>已结束</Select.Option>
                <Select.Option value={ActivityStatus.CANCELED}>已取消</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="maxParticipants"
              label="最大参与人数"
            >
              <InputNumber min={0} style={{ width: '100%' }} placeholder="不填则不限制人数" />
            </Form.Item>

            <Form.Item
              name="registrationDeadline"
              label="报名截止时间"
            >
              <DatePicker
                showTime
                style={{ width: '100%' }}
                placeholder="请选择报名截止时间"
              />
            </Form.Item>
          </div>

          <div className={styles.contentEditor}>
            <Form.Item
              name="content"
              label="活动详情"
              rules={[{ required: true, message: '请输入活动详情' }]}
            >
              <RichTextEditor />
            </Form.Item>
          </div>
        </div>

        <Form.Item className={styles.modalFooter}>
          <Space>
            <Button onClick={() => setModalVisible(false)}>取消</Button>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );

  return (
    <ConfigProvider locale={zhCN}>
      <Card title="活动管理">
        <div className={styles.toolbar}>
          {renderSearchForm()}
        </div>
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          scroll={{ y: 'calc(100vh - 410px)', scrollToFirstRowOnChange: false }}
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['20', '50', '100'],
          }}
          onChange={handleTableChange}
        />
        {renderModal()}
      </Card>
    </ConfigProvider>
  );
};

export default ActivityAdmin; 